'use strict';

const db = uniCloud.database();

exports.main = async (event, context) => {
  console.log('开始清理无效图片URL...');
  
  let cleanedCount = 0;
  let totalChecked = 0;
  
  try {
    // 分批处理，避免一次性查询太多数据
    let skip = 0;
    const limit = 100;
    let hasMore = true;
    
    while (hasMore) {
      // 查询图片消息
      const { data } = await db.collection('customer-service-messages')
        .where({
          messageType: 'image'
        })
        .skip(skip)
        .limit(limit)
        .get();
      
      if (data.length === 0) {
        hasMore = false;
        break;
      }
      
      totalChecked += data.length;
      
      // 处理每条消息
      for (const message of data) {
        let needUpdate = false;
        let newContent = message.content;
        let newImageUrl = message.imageUrl;
        
        // 检查并清理无效的临时路径
        if (message.imageUrl && message.imageUrl.startsWith('http://tmp/')) {
          console.log(`清理无效图片URL: ${message._id}, ${message.imageUrl}`);
          newImageUrl = '';
          needUpdate = true;
        }
        
        if (message.content && message.content.startsWith('http://tmp/')) {
          console.log(`清理无效内容URL: ${message._id}, ${message.content}`);
          newContent = '[图片已失效]';
          needUpdate = true;
        }
        
        // 如果需要更新
        if (needUpdate) {
          try {
            await db.collection('customer-service-messages')
              .doc(message._id)
              .update({
                content: newContent,
                imageUrl: newImageUrl,
                updatedAt: new Date()
              });
            
            cleanedCount++;
            console.log(`已清理消息: ${message._id}`);
          } catch (updateError) {
            console.error(`更新消息失败: ${message._id}`, updateError);
          }
        }
      }
      
      skip += limit;
      console.log(`已处理 ${skip} 条消息，清理了 ${cleanedCount} 条`);
    }
    
    console.log(`清理完成: 检查了 ${totalChecked} 条消息，清理了 ${cleanedCount} 条无效URL`);
    
    return {
      code: 200,
      message: `清理完成: 检查了 ${totalChecked} 条消息，清理了 ${cleanedCount} 条无效URL`,
      data: {
        totalChecked,
        cleanedCount
      }
    };
    
  } catch (error) {
    console.error('清理过程出错:', error);
    return {
      code: 500,
      message: '清理失败: ' + error.message,
      data: {
        totalChecked,
        cleanedCount
      }
    };
  }
};
